package com.aaa.reflection.demo4;

import java.lang.reflect.Field;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: Field类中的具有的相关方法
 * @date 2022/10/27
 */
public class Test01 {
    public static void main(String[] args) throws  Exception {
        Class<Dog> dogClass = Dog.class;
        Dog dog = dogClass.newInstance();
        System.out.println(dog);

        Field sleep = dogClass.getDeclaredField("sleep");
        //为属性赋值
        //通过反射默认对指定属性的对象赋值
        sleep.set(dog,"贪吃");
        System.out.println("sleep = " + sleep);

        //通过反射获取指定属性的对象值
        Object o = sleep.get(dog);
        System.out.println("o ===== " + o);

        Field each = dogClass.getDeclaredField("each");
        //允许访问私有属性
        each.setAccessible(true);
        each.set(dog,25);
        System.out.println("each ==== " + each);

        Object o1 = each.get(dog);
        System.out.println("o1 ==== " + o1);
    }
}


class Cat{
    public String job;
    private Integer age;
}
class Dog extends Cat {
    public String sleep;
    private Integer each;

    @Override
    public String toString() {
        return "Dog{" +
                "sleep='" + sleep + '\'' +
                ", each=" + each +
                '}';
    }
}